package com.zhan.rkforum.controller;


import com.zhan.rkforum.annotation.LoginRequired;
import com.zhan.rkforum.bean.*;
import com.zhan.rkforum.event.EventProducer;
import com.zhan.rkforum.service.CommentService;
import com.zhan.rkforum.service.DiscussPostService;
import com.zhan.rkforum.service.LikeService;
import com.zhan.rkforum.service.UserService;
import com.zhan.rkforum.util.CommunityConstant;
import com.zhan.rkforum.util.CommunityUtil;
import com.zhan.rkforum.util.HostHolder;
import com.zhan.rkforum.util.RedisKeyUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import java.util.*;

@Controller
@RequestMapping("/discuss")
public class DiscussPostController implements CommunityConstant {

    @Autowired
    private DiscussPostService discussPostService;

    @Autowired
    private UserService userService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private CommentService commentService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private LikeService likeService;

    @Autowired
    private EventProducer eventProducer;


    @ResponseBody
    @LoginRequired
    @PostMapping("/add")
    public String addDiscussPost(String title, String content) throws IllegalAccessException {
        User user = hostHolder.getUser();
        if(ObjectUtils.isEmpty(user)){
            return CommunityUtil.getJsonString(403,"您还没有登录哦");
        }
        if(StringUtils.isEmpty(title) || StringUtils.isEmpty(content)){
            return CommunityUtil.getJsonString(402, "参数不能为空");
        }
        DiscussPost post = new DiscussPost();
        post.setUserId(String.valueOf(user.getId()));
        post.setTitle(title);
        post.setContent(content);
        post.setType(0);
        post.setStatus(0);
        post.setCreateTime(new Date());
        post.setCommentCount(0);
        post.setScore(0);
        discussPostService.addDiscussPost(post);

        //触发消息队列
        Event event = new Event();
        event.setTopic(TOPIC_PUBLISH)
                .setEntityType(ENTITY_TYPE_POST)
                .setUserId(user.getId())
                .setEntityId(post.getId());
        eventProducer.fireEvent(event);

        String postScoreKey = RedisKeyUtil.getPostScoreKey();
        redisTemplate.opsForSet().add(postScoreKey, post.getId());

        return CommunityUtil.getJsonString(0,"发布成功！");

    }


    @GetMapping("/detail/{id}")
    public String getDetailDiscuss(@PathVariable("id") int postId, Model model, Page page){
        //帖子信息
        DiscussPost post = discussPostService.findDiscussPostById(postId);
        model.addAttribute("post",post);
        //作者信息
        User user = userService.findUserById(Integer.parseInt(post.getUserId()));
        model.addAttribute("user",user);
        //点赞
        model.addAttribute("postLikeCount",likeService.getEntityLikeCount(ENTITY_TYPE_POST, post.getId()));
        //评论信息
        page.setLimit(5);
        page.setPath("/discuss/detail/" + postId);
        page.setRows(post.getCommentCount());

        //帖子内部评论信息
        List<Comment> commentList = commentService.selectCommentByEntity(ENTITY_TYPE_POST, post.getId(),page.getOffset(), page.getLimit());
        //返回给前端的评论列表
        List<Map<String, Object>> commentVoList = new ArrayList<>();
        if(ObjectUtils.isNotEmpty(commentList)){
            for (Comment comment : commentList) {
                //评论信息
                HashMap<String, Object> commentMap = new HashMap<>();
                commentMap.put("comment", comment);
                commentMap.put("user", userService.findUserById(comment.getUserId()));

                //回复信息
                List<Comment> replyList = commentService.selectCommentByEntity(ENTITY_TYPE_COMMENT, comment.getId(), 0, Integer.MAX_VALUE);
                List<HashMap<String, Object>> replies = new ArrayList<>();
                if(ObjectUtils.isNotEmpty(replyList)){
                    for (Comment reply : replyList) {
                        HashMap<String, Object> replyMap = new HashMap<>();
                        replyMap.put("reply", reply);
                        replyMap.put("user", userService.findUserById(reply.getUserId()));
                        replyMap.put("targetUser", userService.findUserById(reply.getTargetId()));
                        Long likeCount = likeService.getEntityLikeCount(ENTITY_TYPE_COMMENT, reply.getId());
                        replyMap.put("replyLikeCount",likeCount);
                        replies.add(replyMap);
                    }
                }
                commentMap.put("replies", replies);
                commentMap.put("replyCount", commentService.selectCommentCountByEntity(ENTITY_TYPE_COMMENT, comment.getId()));
                commentVoList.add(commentMap);
            }
        }
        model.addAttribute("comments", commentVoList);

        return "/site/discuss-detail";
    }

    //置顶
    @PostMapping(value = "/top")
    @ResponseBody
    public String setTop(int id){
        discussPostService.updateType(id, 1);
        //触发消息队列：发帖事件
        Event event = new Event();
        event.setTopic(TOPIC_PUBLISH)
                .setEntityType(ENTITY_TYPE_POST)
                .setUserId(hostHolder.getUser().getId())
                .setEntityId(id);
        eventProducer.fireEvent(event);
        return CommunityUtil.getJsonString(0);
    }

    //加精
    @PostMapping(value = "/refining")
    @ResponseBody
    public String setRefining(int id){
        discussPostService.updateStatus(id, 1);

        //触发消息队列：发帖事件
        Event event = new Event();
        event.setTopic(TOPIC_PUBLISH)
                .setEntityType(ENTITY_TYPE_POST)
                .setUserId(hostHolder.getUser().getId())
                .setEntityId(id);
        eventProducer.fireEvent(event);
        //计算贴子分数
        String postScoreKey = RedisKeyUtil.getPostScoreKey();
        redisTemplate.opsForSet().add(postScoreKey, id);

        return CommunityUtil.getJsonString(0);
    }

    //删除
    @PostMapping(value = "/delete")
    @ResponseBody
    public String deleteDiscussPost(int id){
        discussPostService.updateStatus(id, 2);

        //触发消息队列：删帖事件
        Event event = new Event();
        event.setTopic(TOPIC_DELETE)
                .setEntityType(ENTITY_TYPE_POST)
                .setUserId(hostHolder.getUser().getId())
                .setEntityId(id);
        eventProducer.fireEvent(event);
        return CommunityUtil.getJsonString(0);
    }




}
